<?php

class storageHelper extends helperBase {
	protected $spKey, $lpKey;

	function init() {
		if(isset($_SESSION['key'])) {
			$this->spKey = $_SESSION['key'];
		} else {
			$this->spKey = $_SESSION['key'] = generateKey();
		}

		if(isset($_COOKIE['key'])) {
			$this->lpKey = $_COOKIE['key'];
		} else {
			$this->lpKey = generateKey();
		}
		setcookie('key', $this->lpKey, time() + 60 * 60 * 24 * 14, $this->aether->config->get('general', 'webRoot'));
	}

	function get($name) {
		if(!$result = $this->m->storage->get('all', array(
			'columns' => array('id', 'value'),
			'where' => new constraint(
				new predicate('name', '=', $name),
				'&&',
				new constraint(
					new predicate('key', '=', $this->spKey),
					'||',
					new predicate('key', '=', $this->lpKey)
				)
			),
			'results' => 'SINGLE'
		))) {
			return false;
		}
		$this->lastId = $result['id'];
		return json_decode($result['value']);
	}

	function set($name, $value, $lp = true, $expires = null) {
		if(!$expires) {
			$expires = time() + 60 * 60 * 24;
		}
		if($lp) {
			$key = $this->lpKey;
		} else {
			$key = $this->spKey;
		}
		if($this->get($name)) {
			return $this->m->storage->update($this->lastId, new data(array(
				'value' => json_encode($value),
				'expires' => $expires,
				'key' => $key
			)));
		} else {
			return $this->m->storage->insert(new data(array(
				'name' => $name,
				'value' => json_encode($value),
				'expires' => $expires,
				'key' => $key
			)));
		}
	}

}

?>
